#!/usr/bin/env python
# -*- coding: utf-8> -*-

from BeautifulSoup import BeautifulSoup
import urllib2
import json
import time
from urllib2 import HTTPError

def crawlMovie(hyperlink):
    moviesoup = None
    while True:
        try:  
            web = urllib2.urlopen(url = hyperlink, timeout = 60)
            moviesoup = BeautifulSoup(web.read())
            web.close()
            break
        except:
            pass

    movie_attrs = {}
    
    movie_id = hyperlink.split('=')[-1]
    movie_attrs['id'] = movie_id
    
    movie_div = moviesoup.find( name = 'div', attrs = { 'id' : 'ymvmvf', 'class' : 'ymvmodule' } )

    #Url of movie poster
    pic_div = movie_div.find( name = 'div', attrs = { 'class' : 'img' })
    movie_attrs['mini_pic_href'] = pic_div.find( name = 'img' )['src']
    movie_attrs['big_pic_href']  = pic_div.find( name = 'a' )['href']

    #Get information of the movie
    text_div = movie_div.find( name = 'div', attrs = { 'class' : 'text bulletin' } )
    movie_attrs['title_ch'] = unicode(text_div.find( name = 'h4' ).string)
    movie_attrs['title_en'] = unicode(text_div.find( name = 'h5' ).string)
    ps = text_div.findAll( name = 'p' )
    for p in ps:
        title = unicode(p.find( name = 'span', attrs = { 'class' : 'tit' }).find(text=True).string)
        data  = unicode(p.find( name = 'span', attrs = { 'class' : 'dta' }).find(text=True).string)   
        if title == u'上映日期：':
            movie_attrs['in_theater'] = data
        if title == u'類　　型：':
            movie_attrs['genre'] = data
        if title == u'片　　長：':
            movie_attrs['run_time'] = data
        if title == u'導　　演：':
            movie_attrs['director'] = data
        if title == u'演　　員：':
            movie_attrs['cast'] = data                                               
    #Movie introduction
    movie_attrs['synopsis'] = unicode(moviesoup.find( name = 'div', attrs = { 'class' : 'text full' } ))
    movie_attrs['times'] = getMovieTimesByMovieId(movie_attrs['id']) #A list of times
    
    
    '''
    text_div = moviesoup.find( name = 'div', attrs = { 'class' : 'text full' } )
    currentTag = text_div
    synopsis = ''
    while currentTag != None:
        #synopsis += 'XD'
        if hasattr(currentTag, 'string') and currentTag.string != None:
            synopsis += currentTag.string
        elif hasattr(currentTag, 'name') and currentTag.name == 'br':
            synopsis += '\n'
        currentTag = currentTag.next
         
    #movie_attrs['synopsis'] = unicode(synopsis)
    '''
    return movie_attrs

def getTimesHyperlink(movie_id):
    return 'http://tw.movie.yahoo.com/movietime_result.html?id=' + movie_id

def getMovieTimesByMovieId(movie_id):
    
    timesoup = None
    while True:
        try:
            hyperlink = getTimesHyperlink(movie_id)
            web = urllib2.urlopen(url = hyperlink, timeout = 10)
            timesoup = BeautifulSoup(web.read())
            web.close()
            break
        except HTTPError as e:
            pass
            #return e.geturl()    
    
    row_divs = timesoup.findAll(name = 'div', attrs = { 'class' : 'row' })
    results = []
    for row_div in row_divs:
        attrs = {}
        times = []         
        linkTag = row_div.find(name = 'a')
        theater_name = unicode(linkTag.string)
        theater_id = unicode(linkTag['href'].split('=')[-1])        
        theater_phone_number = unicode(row_div.find(name = 'p').string)
        timeTags = row_div.findAll( name = 'span', attrs = { 'class' : 'tmt' })
        for timeTag in timeTags:
            times.append(unicode(timeTag.string))
        attrs['movie_id'] = movie_id   
        attrs['theater_hyperlink'] = unicode(linkTag['href'])
        #attrs['theater_hyperlink'] = linkTag
        attrs['theater_name'] = theater_name
        attrs['theater_id'] = theater_id
        attrs['theater_phone_number'] = theater_phone_number
        attrs['times'] = times 
        #attrs['times'] = ','.join(times)
        results.append(attrs)
    
    return results    
    #json_str = json.dumps( results, ensure_ascii = False )
    #return json_str


